package app;

import java.io.*;
import java.util.*;

import android.view.View.OnClickListener;
import android.view.View;

import org.w3c.dom.*;

import com.StarMicronics.StarIOSDK.R;

import android.app.*;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import utils.*;

public class LoginServer implements  RequestListener, NotificationListener {
	private WaittingAlertView waittingAlertView;
	private static LoginServer sharedInstance;
	private final static String SERVER_URL = "http://paperlessapi.c1.concretego.com";
	
	public Activity activity;
	
	public Vector<Dictionary<String, String>> data;
	
	
	public String savePath() {
		return "server.db";
	}
	
	public LoginServer() {
	}
	
	public void construct() {
		data = new Vector<Dictionary<String, String>>();
		this.loadFormCache();
		AppDelegate.sharedInstance().addNotificationListener(MultiLanguageChangeNotificationListener.class, this);
		
		boolean find = false;
		for (int i = 0; i < data.size(); i++) {
			Dictionary<String, String> item = (Dictionary<String, String>) data.elementAt(i);
			if (item != null) {
				String url = item.get("url");
				if (url != null) {
					if (url.equals(SERVER_URL)) {
						find = true;
						break;
					}
				}
			}
		}
		
		if (find == false) {
			Dictionary<String, String> item = new Hashtable<String, String>();
			item.put("name", "");
			item.put("url", SERVER_URL);
			data.add(item);
		}
		
		
		waittingAlertView = WaittingAlertView.createWaittingAlertView();
		waittingAlertView.button.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		retry();
        	}
		});
		waittingAlertView.button.setText(FilePack.getStringByID(STRING_ID.STR_RETRY));
		waittingAlertView.setLoadingText(null);
		waittingAlertView.show();
		AppDelegate.sharedInstance().sendHttpRequest("getServerList?", null, this);
	}
	
	
	public void addServerWithName(String name, String url) {
		if (name == null) name = "";
		if (url == null) url = "";
		Dictionary<String, String> item = new Hashtable<String, String>();
		item.put("name", name);
		item.put("url", url);
		item.put("changable", "1");
		data.add(item);
		this.saveToCache();
		
		AppDelegate.sharedInstance().postNotification(DataSourceChangeNotificationListener.class, this, null);
	}
	
	public void removeServerWithIndex(int index) {
		if (index >= 0 && index < data.size()) {
			data.removeElementAt(index);
			this.saveToCache();
			AppDelegate.sharedInstance().postNotification(DataSourceChangeNotificationListener.class, this, null);
		}
	}

	public static LoginServer sharedInstance() {
		if (sharedInstance == null) {
			sharedInstance = new LoginServer();
			sharedInstance.construct();
		}
		return sharedInstance;
	}

	
	private void showRetry(String error) {
		if (waittingAlertView != null) {
			waittingAlertView.setTitle(error);
		}
	}
	
	public void requestFinished(RequestItem request, Dictionary<String, Object> params,
			Element xml, boolean successfull) {
		if (successfull) {
			if (XMLReader.getIntForKey(xml, "ret", 0) == 1) {
				String connected_url = null;
				for (int i = 0; i < data.size(); i++) {
					Dictionary<String, String> dic = data.elementAt(i);
					if (dic.get("connected") != null) {
						connected_url = dic.get("url");
						break;
					}
				}
				
				int count = data.size();
				for (int i = 0; i < count; i++) {
					Dictionary<String, String> dic = data.elementAt(i);
					if (dic.get("changable") == null) {
						data.removeElementAt(i);
						i--;
						count--;
					}
				}
				Vector<Node> nList = XMLReader.getNodeList(xml, "Servers");
				if (nList != null) {
					count = nList.size();
					for (int i = count - 1; i >= 0; i--) {
						Element node = (Element)nList.elementAt(i);
						String name = XMLReader.getStringForKey(node, "Name", null);
						String url = XMLReader.getStringForKey(node, "Url", null);
						if (name != null && url != null) {
							Dictionary<String, String> item = new Hashtable<String, String>();
							item.put("name", name);
							item.put("url", url);
							data.add(item);
						}
					}
				}
				
				boolean find = false;
				for (int i = 0; i < data.size(); i++) {
					Dictionary<String, String> dic = data.elementAt(i);
					if (dic.get("url").equals(SERVER_URL)) {
						find =  true;
						break;
					}
				}
				if (find == false) {
					Dictionary<String, String> item = new Hashtable<String, String>();
					item.put("name", "");
					item.put("url", SERVER_URL);
					data.add(item);
				}
				
				if (connected_url != null) {
					for (int i = 0; i < data.size(); i++) {
						Dictionary<String, String> dic = data.elementAt(i);
						if (connected_url.equals(dic.get("url"))) {
							dic.put("connected", "1");
							break;
						}
					}
				}

				
				this.saveToCache();
				AppDelegate.sharedInstance().postNotification(DataSourceChangeNotificationListener.class, this, null);
				if (waittingAlertView != null) waittingAlertView.cancel();
				waittingAlertView = null;
			} else {
				this.showRetry(XMLReader.getStringForKey(xml, "error", FilePack.getStringByID(STRING_ID.STR_ERROR_OCCUR)));
			}
		} else {
			this.showRetry(FilePack.getStringByID(STRING_ID.STR_ERROR_OCCUR));
		}
	}
	
	private void retry() {
		waittingAlertView.setLoadingText(null);
		AppDelegate.sharedInstance().sendHttpRequest("getServerList?", null, this);
	}
	
	private void saveToCache() {
		try {
			SQLiteDatabase db = AppDelegate.sharedInstance().activity.openOrCreateDatabase(this.savePath(), Context.MODE_PRIVATE, null);
			try {
				db.execSQL("DROP TABLE tab");
			} catch (Exception e){}
			db.execSQL("create table tab(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, server TEXT, changable INTEGER)");
			//db.execSQL("DELETE * FROM tab");
			//ContentValues values = new ContentValues();
			for (int i = 0; i < data.size(); i++) {
				Dictionary<String, String> dic = data.elementAt(i);
				String name = dic.get("name");
				String url = dic.get("url");
				String changable = dic.get("changable");
				if (url != null) {
					//if (name != null) values.put("name", name);
					//if (changable != null) values.put("changable", Integer.valueOf(1));
					//values.put("url", url);
					//db.insert("tab", "_id", values);
					db.execSQL("insert into tab(name, server, changable) values(?,?,?)", new Object[]{name, url, changable});
				}
			}
			db.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void loadFormCache() {
		data.removeAllElements();		
		try {
			SQLiteDatabase db = AppDelegate.sharedInstance().activity.openOrCreateDatabase(this.savePath(), Context.MODE_PRIVATE, null);
			Cursor c = db.query("tab", null, null, null, null, null, null);//db.rawQuery("select * from tab", null);
			c.moveToFirst();
			while(!c.isAfterLast()){
				int index = c.getColumnIndex("name");
				String name = c.getString(index);
				index = c.getColumnIndex("server");
				String url = c.getString(index);
				index = c.getColumnIndex("changable");
				int changable = c.getInt(index);
				c.moveToNext();
				
				Dictionary<String, String> dic = new Hashtable<String, String>();
				if (name != null) dic.put("name", name);
				if (url != null) dic.put("url", url);
				if (changable == 1) dic.put("changable", "1");
				data.add(dic);
			}
			db.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void notification(Class clss, Object object, Object userInfo) {
		// TODO Auto-generated method stub
		if (clss == MultiLanguageChangeNotificationListener.class) {
			AppDelegate.sharedInstance().sendHttpRequest("getServerList?&Language="+FilePack.currentLanguageString(), null, this);
		}
	}
}
